package com.ukefu.webim.web.handler.apps.report;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.util.Menu;
import com.ukefu.webim.service.repository.DataDicRepository;
import com.ukefu.webim.service.repository.OrganRepository;
import com.ukefu.webim.service.repository.PublishedReportRepository;
import com.ukefu.webim.service.repository.ReportAuthRepository;
import com.ukefu.webim.service.repository.ReportCubeService;
import com.ukefu.webim.service.repository.UserRoleRepository;
import com.ukefu.webim.util.CallCenterUtils;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.DataDic;
import com.ukefu.webim.web.model.PublishedReport;
import com.ukefu.webim.web.model.ReportAuth;
import com.ukefu.webim.web.model.ReportFilter;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.UserRole;

@Controller
@RequestMapping("/apps/view")
public class ReportViewController extends Handler{
	
	@Value("${web.upload-path}")
    private String path;
	
	@Value("${uk.im.server.port}")  
    private Integer port; 
	
	@Autowired
	private DataDicRepository dataDicRes;
	
	@Autowired
	private PublishedReportRepository publishedReportRes;
	
	@Autowired
	private ReportCubeService reportCubeService;
	
	@Autowired
	private OrganRepository organRepository; 
	
	@Autowired
	private ReportAuthRepository reportAuthRes;
	
	@Autowired
	private UserRoleRepository userRoleRes;
	
    @RequestMapping("/index")
    @Menu(type = "setting" , subtype = "report" )
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String dicid , @Valid String id) throws Exception {
    	String orgi = super.getOrgi(request);

    	Page<PublishedReport> publishedReportList = null ;
    	if(!StringUtils.isBlank(dicid) && !"0".equals(dicid)){
        	map.put("dataDic", dataDicRes.findByIdAndOrgi(dicid, orgi)) ;
    	}
    	
    	User user = super.getUser(request);//当前用户
    	String organ = user.getOrgan();//当前用户所属部门
    	String userid = user.getId();//当前用户id
    	List<UserRole> userroleList = userRoleRes.findByOrgiAndUser(orgi, user);
    	List<String> roleids = new ArrayList<>();//当前用户所属角色id
    	if (userroleList!=null && userroleList.size() > 0) {
    		for(UserRole ur:userroleList){
    			if (ur.getRole()!=null) {
    				roleids.add(ur.getRole().getId());
				}
    		}
		}
    	
    	List<DataDic> dataDicList = new ArrayList<DataDic>();
    	List<DataDic> tempdataDicList = dataDicRes.findByOrgi(orgi);
    	if (tempdataDicList != null && tempdataDicList.size() > 0) {
			for(DataDic dic : tempdataDicList){
				if (dic.isUserauth()) {
					ReportAuth rauth = reportAuthRes.findByDicidAndOrgi(dic.getId(), super.getOrgi(request));
					if (rauth != null) {
						if (!StringUtils.isBlank(rauth.getAuthorgan()) && !StringUtils.isBlank(organ) && rauth.getAuthorgan().indexOf(organ)!=-1) {
							dataDicList.add(dic);
							continue;
						}
						if (!StringUtils.isBlank(rauth.getAuthrole()) && roleids!=null && roleids.size() > 0) {
							boolean ic = false;
							for(String roleid : roleids){
								if (rauth.getAuthrole().indexOf(roleid)!=-1) {
									dataDicList.add(dic);
									ic = true;
									break;
								}
							}
							if (ic) {
								continue;
							}
						}
						if (!StringUtils.isBlank(rauth.getAuthuser()) && !StringUtils.isBlank(userid) && rauth.getAuthuser().indexOf(userid)!=-1) {
							dataDicList.add(dic);
							continue;
						}
					}
				}else{
					dataDicList.add(dic);//把没开启用户查看权限的菜单直接放入list
				}
			}
		}
    	if (user.isSuperuser()) {
    		map.put("dataDicList", tempdataDicList) ;
		}else{
			map.put("dataDicList", dataDicList) ;
		}
    	
    	publishedReportList = publishedReportRes.findByOrgi(orgi , new PageRequest(super.getP(request), super.getPs(request)));
    	if (user.isSuperuser()) {
    		map.put("reportList", publishedReportList);
		}else{
			List<String> reportids = new ArrayList<>();
	    	for(PublishedReport preport : publishedReportList){
	    		DataDic currdic = dataDicRes.findByIdAndOrgi(preport.getDicid(), orgi);
	    		if (preport.isUserauth() && currdic!=null && currdic.isUserauth()) {
					ReportAuth rauth = reportAuthRes.findByReportAndOrgi(preport.getId(), super.getOrgi(request));
					if (rauth != null) {
						if (!StringUtils.isBlank(rauth.getAuthorgan()) && !StringUtils.isBlank(organ) && rauth.getAuthorgan().indexOf(organ)!=-1) {
							reportids.add(preport.getId());
							continue;
						}
						if (!StringUtils.isBlank(rauth.getAuthrole()) && roleids!=null && roleids.size() > 0) {
							boolean ic = false;
							for(String roleid : roleids){
								if (rauth.getAuthrole().indexOf(roleid)!=-1) {
									reportids.add(preport.getId());
									ic = true;
									break;
								}
							}
							if (ic) {
								continue;
							}
						}
						if (!StringUtils.isBlank(rauth.getAuthuser()) && !StringUtils.isBlank(userid) && rauth.getAuthuser().indexOf(userid)!=-1) {
							reportids.add(preport.getId());
							continue;
						}
					}
				}else{
					reportids.add(preport.getId());
				}
	    	}
	    	if (reportids != null && reportids.size() >0 && !user.isSuperuser()) {
				map.put("reportList", publishedReportList = publishedReportRes.findByIdIn(reportids,new PageRequest(super.getP(request), 100))) ;
			}
		}
    	
    	if(publishedReportList!=null && publishedReportList.getContent().size() > 0) {
    		PublishedReport publishedReport = null;
    		if (!user.isSuperuser()) {
    			boolean hr = false;
    			for(PublishedReport preport:publishedReportList){
        			if (dataDicList != null && dataDicList.size() > 0) {
    					for(DataDic dic:dataDicList){
    						if (!StringUtils.isBlank(preport.getDicid()) && preport.getDicid().equals(dic.getId())) {
    							publishedReport = preport;
    							hr = true;
    							break;
    	    				}
    					}
    					if (hr) {
							break;
						}
    				}
        		}
    		}else{
    			publishedReport = publishedReportList.getContent().get(0);
    		}
    		
    		if(!StringUtils.isBlank(id)) {
    			for(PublishedReport report : publishedReportList) {
    				if(report.getId().equals(id)) {
    					publishedReport = report ; break ;
    				}
    			}
    		}
    		map.put("report", publishedReport) ;
    		map.addAttribute("organList", organRepository.findByOrgi(super.getOrgi(request)));
    		if(publishedReport!=null) {
				map.addAttribute("publishedReport", publishedReport);
				map.addAttribute("report", publishedReport.getReport());
				map.addAttribute("reportModels", publishedReport.getReport().getReportModels());
				List<ReportFilter> listFilters = publishedReport.getReport().getReportFilters();
				if(!listFilters.isEmpty()) {
					Map<String,ReportFilter> filterMap = new HashMap<String,ReportFilter>();
					for(ReportFilter rf:listFilters) {
						filterMap.put(rf.getId(), rf);
					}
					for(ReportFilter rf:listFilters) {
						if(!StringUtils.isBlank(rf.getCascadeid())) {
							rf.setChildFilter(filterMap.get(rf.getCascadeid()));
						}
						if (rf.isDataauth()) {
							List<String> organList = CallCenterUtils.getExistOrgan(super.getUser(request));
							map.addAttribute("organList", organRepository.findAll(organList));
						}
					}
				}
				map.addAttribute("reportFilters", reportCubeService.fillReportFilterData(listFilters, request));
			}
    		
    	} 
		
    	return request(super.createRequestPageTempletResponse("/apps/business/view/index"));
    }
    
    @RequestMapping("/console")
    @Menu(type = "setting" , subtype = "report" )
    public ModelAndView console(ModelMap map , HttpServletRequest request , @Valid String dicid , @Valid String id) throws Exception {
    	PublishedReport publishedReport = publishedReportRes.findById(id);
		if(publishedReport!=null) {
			map.addAttribute("publishedReport", publishedReport);
			map.addAttribute("report", publishedReport.getReport());
			map.addAttribute("reportModels", publishedReport.getReport().getReportModels());
			List<ReportFilter> listFilters = publishedReport.getReport().getReportFilters();
			if(!listFilters.isEmpty()) {
				Map<String,ReportFilter> filterMap = new HashMap<String,ReportFilter>();
				for(ReportFilter rf:listFilters) {
					filterMap.put(rf.getId(), rf);
				}
				for(ReportFilter rf:listFilters) {
					if(!StringUtils.isBlank(rf.getCascadeid())) {
						rf.setChildFilter(filterMap.get(rf.getCascadeid()));
					}
				}
			}
			map.addAttribute("reportFilters", reportCubeService.fillReportFilterData(listFilters, request));
		}
    	
    	return request(super.createRequestPageTempletResponse("/apps/business/view/console"));
    }
}